<?php

class Query {
    
    /**
     * @var DbConnection
     */
    protected $Connection;
    protected $sql;
    protected $resource;

    public function __construct(DbConnection $Connection, $sql='') {
        $this->Connection = $Connection;
        $this->sql = $sql;
    }
    
    public function __destruct() {
        $this->freeResult();
    }
    
    public function getSql() {
        return $this->sql;
    }

    public function setSql($sql) {
        $this->sql = $sql;
        $this->freeResult();
    }

    public function execute() {
        $this->resource = pg_query($this->Connection->getResource(), $this->sql);
        if (!$this->resource) {
            throw new EstruturaException('Erro ao executar o SQL: '.$this->sql. ' ERRO: '.$this->lastError());
        }
        return ($this->resource);
    }
    
    public function fetchObject() {
        return pg_fetch_object($this->resource);
    } 
    
    public function escapeString($text,$quote=true) {
        if ($text === '') {
            return 'NULL';
        }
        else {
            if ($quote) {
                return "'".pg_escape_string($this->Connection->getResource(), $text)."'";                
            }
            else {
                return pg_escape_string($this->Connection->getResource(), $text);                
            }

        }
    }
    
    public function lastError() {
        //return pg_last_error($this->Connection->getResource());
        if ($aError = error_get_last()) {
            return $aError['message'];
        }
    }


    public function freeResult() {
        if ($this->resource) {
            pg_free_result($this->resource);
            $this->resource = null;
        }
        
    }
    
    public function next($table,$field,$cond='') {
        $sql = "select coalesce(max($field), 0) + 1 as next from $table";
        if ($cond) {
            $sql .= " where " . $cond;
        }
        $this->setSql($sql);
        $this->execute();
        if ($oRes = $this->fetchObject()) {
            return $oRes->next;
        }
        return 1;
    }
    
    
}

?>
